package com.omg.server.framework.scheduler;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.BlockingQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.omg.server.crawler.RequestContext;
import com.omg.server.framework.service.IDefaultService;
import com.omg.server.util.CommonUtil;
/**
 * 生成抓取数据请求(生产者)定时器服务
 *
 */
public class CrawlerRequestJobService implements CrawlerRequestJob{
	private static final Log log = LogFactory.getLog(CrawlerRequestJobService.class);
	private IDefaultService defaultService;
	private BlockingQueue<RequestContext> requestQueue;
	public static final String THREANAMEPREFIX = "scheduler_Worker-";
	

	@Override
	public void extractRequest() {
		
		//当前线程中线程池中的序号
		String threadNo = Thread.currentThread().getName().substring(THREANAMEPREFIX.length());
		try {
			//查询抓取请求任务
			//String fetchSize = PropertiesHelper.getProperty(Constants.REQUESTTASKFETCHSIZE);
			//log.info("配置每次获取的请求数: " + fetchSize);
			//int size = 100;//一次取的记录数量默认值
			//if(CommonUtil.isNumber(fetchSize)){
				//size = Integer.valueOf(fetchSize);
			//}
			
			//Map<String, Object> params = new HashMap<String, Object>(1);
			List<RequestContext> list = defaultService.find_iBatis("omg.crawler.getRequestTaskList", null);
			int recordCount = 0;
			//生成处理请求并将数据库的任务队列进行迁移
			if (CommonUtil.isNotEmpty(list)){
				recordCount = list.size();
				Iterator<RequestContext> it = list.iterator();
				RequestContext rc = null;
				
				while(it.hasNext()){
					rc = it.next();
					this.requestQueue.offer(rc); //非阻塞入队列
				}
				
				log.info("生成请求队列成功， 请求数:" + recordCount);
			}
			
			log.info("生成请求队列完成, 线程号:" + threadNo +", 任务数:"+recordCount);
			
		}
		catch (Exception e) {
			log.error("生成请求队列失败", e);
		}
		finally{
		}
		
	}
	
	public BlockingQueue<RequestContext> getRequestQueue() {
		return requestQueue;
	}

	public void setRequestQueue(BlockingQueue<RequestContext> requestQueue) {
		this.requestQueue = requestQueue;
	}

	public IDefaultService getDefaultService() {
		return defaultService;
	}

	public void setDefaultService(IDefaultService defaultService) {
		this.defaultService = defaultService;
	}
	
	public static void main(String[] args){
		new CrawlerRequestJobService().extractRequest();
	}
    
}
